package com.wx.business.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import com.alibaba.fastjson.JSONObject;
import com.wx.business.WXConfig;

public class WXHttpUtil {
	
	/**
	 * 获取AccessToken
	 * @return
	 */
	public static String requestAccessToken() {
		String httpUrl = "https://api.weixin.qq.com/cgi-bin/token";
	    BufferedReader reader = null;
	    String result = null;
	    StringBuffer sbf = new StringBuffer();
	    httpUrl = httpUrl + "?grant_type=client_credential&appid="+WXConfig.AppID+"&secret="+WXConfig.AppSecret ;

	    try {
	        URL url = new URL(httpUrl);
	        HttpURLConnection connection = (HttpURLConnection) url
	                .openConnection();
	        connection.setRequestMethod("POST");
	        connection.connect();
	        InputStream is = connection.getInputStream();
	        reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
	        String strRead = null;
	        while ((strRead = reader.readLine()) != null) {
	            sbf.append(strRead);
	            sbf.append("\r\n");
	        }
	        reader.close();
	        result = sbf.toString();
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    return result;
	}
	
	
	/**
	 * 获取AccessToken
	 * @return
	 */
	public static String requestTicket(String accessToken) {
		String httpUrl =WXConfig.H5WX_SHARETICKET_URL;
	    BufferedReader reader = null;
	    String result = null;
	    StringBuffer sbf = new StringBuffer();
	    httpUrl = httpUrl + "?access_token="+accessToken+"&type=jsapi";

	    try {
	        URL url = new URL(httpUrl);
	        HttpURLConnection connection = (HttpURLConnection) url
	                .openConnection();
	        connection.setRequestMethod("POST");
	        connection.connect();
	        InputStream is = connection.getInputStream();
	        reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
	        String strRead = null;
	        while ((strRead = reader.readLine()) != null) {
	            sbf.append(strRead);
	            sbf.append("\r\n");
	        }
	        reader.close();
	        result = sbf.toString();
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    return result;
	}
	
	
	
	/**
	 * 根据code获取token
	 * @param code
	 * @return
	 */
	public static String requestCodeToken(String code) {
		String httpUrl = "https://api.weixin.qq.com/sns/oauth2/access_token";
	    BufferedReader reader = null;
	    String result = null;
	    StringBuffer sbf = new StringBuffer();
	    httpUrl = httpUrl + "?appid="+WXConfig.AppID+"&secret="+WXConfig.AppSecret+"&code="+code+"&grant_type=authorization_code" ;

	    try {
	        URL url = new URL(httpUrl);
	        HttpURLConnection connection = (HttpURLConnection) url
	                .openConnection();
	        connection.setRequestMethod("POST");
	        connection.connect();
	        InputStream is = connection.getInputStream();
	        reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
	        String strRead = null;
	        while ((strRead = reader.readLine()) != null) {
	            sbf.append(strRead);
	            sbf.append("\r\n");
	        }
	        reader.close();
	        result = sbf.toString();
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    return result;
	}
	
	

	/**
	 * 根据用户openId 和accessToken 获取用户的信息
	 * @param openid
	 * @param accessToken
	 * @return
	 */
	public static String requestUserInfo(String openid,String accessToken) {
		String httpUrl = "https://api.weixin.qq.com/sns/userinfo";
	    BufferedReader reader = null;
	    String result = null;
	    StringBuffer sbf = new StringBuffer();
	    httpUrl = httpUrl + "?openid="+openid+"&access_token="+accessToken+"&lang=zh_CN";

	    try {
	        URL url = new URL(httpUrl);
	        HttpURLConnection connection = (HttpURLConnection) url
	                .openConnection();
	        connection.setRequestMethod("GET");
	        connection.connect();
	        InputStream is = connection.getInputStream();
	        reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
	        String strRead = null;
	        while ((strRead = reader.readLine()) != null) {
	            sbf.append(strRead);
	            sbf.append("\r\n");
	        }
	        reader.close();
	        result = sbf.toString();
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    return result;
	}
	
	

	/**
	 * 根据用户openId 和accessToken 获取用户的Code
	 * appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
	 * @param appid
	 * @param redirect_uri
	 * @param state
	 * @return
	 */
	public static String requestAuthCode(String appid,String redirect_uri,String state) {
		String httpUrl = WXConfig.auth_url;
	    httpUrl = httpUrl + "?appid="+appid+"&redirect_uri="+redirect_uri+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
	    return httpUrl;
	}
	
	/**

	 * 发送模板消息

	 * @param accessToken

	 * @param jsonData

	*/

	public static void sendTemplateMsg(String accessToken,String jsonData){

	String requestUrl="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
	
	requestUrl=requestUrl.replace("ACCESS_TOKEN", accessToken);
	JSONObject jsonObject = httpRequest(requestUrl,"GET", jsonData);
	if(jsonObject!=null){
	if("0".equals(jsonObject.getString("errcode"))){
	System.out.println("发送模板消息成功！");

	}else{
	System.out.println(jsonObject.getString("errcode"));
         }
	  }
	}
	

	/**

	 * 发起https请求并获取结果
	 * @param requestUrl 请求地址
	 * @param requestMethod 请求方式（GET、POST）
	 * @param outputStr 提交的数据
	 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
	*/
	public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {

	JSONObject jsonObject = null;
	StringBuffer buffer = new StringBuffer();

	try {
	
		URL url = new URL(requestUrl);
		HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
		httpUrlConn.setDoOutput(true);
		httpUrlConn.setDoInput(true);
		httpUrlConn.setUseCaches(false);
	
		// 设置请求方式（GET/POST）
		httpUrlConn.setRequestMethod(requestMethod);
	
		if ("GET".equalsIgnoreCase(requestMethod))
		     httpUrlConn.connect();
	
	         // 当有数据需要提交时
		    if (null != outputStr) {
		      OutputStream outputStream = httpUrlConn.getOutputStream();
		       // 注意编码格式，防止中文乱码
		      outputStream.write(outputStr.getBytes("UTF-8"));
		      outputStream.close();
		}
	
		// 将返回的输入流转换成字符串
		InputStream inputStream = httpUrlConn.getInputStream();
		InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"utf-8");
		BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
		String str = null;
		while ((str = bufferedReader.readLine()) != null) {
		buffer.append(str);
		}
	
		bufferedReader.close();
		inputStreamReader.close();
	
		// 释放资源
		inputStream.close();
		inputStream = null;
		httpUrlConn.disconnect();
		
	} catch (ConnectException ce) {

	} catch (Exception e) {

	}

	return JSONObject.parseObject(buffer.toString());

	}
	
}
